# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '592072414555143': {  # witch 支付宝3.5%（10---3000），qq1.8%（10---1000）。do结算 新 鑫支付
        'API_KEY': '06F4528B3767B8D46E4848B7695975D620180724145551',
        'gateway': 'http://xinfugood.com:8081/trade/doPay.do',
        'query_gateway': 'http://xinfugood.com:8081/trade/quickQuery.do',
    },
    '5920724164602720': {  # loki 支付宝3.5%（10---3000），qq1.8%（10---1000）。do结算 新 鑫支付
        'API_KEY': '595C531680A56C063A13E1230309ACB620180724164602',
        'gateway': 'http://xinfugood.com:8081/trade/doPay.do',
        'query_gateway': 'http://xinfugood.com:8081/trade/quickQuery.do',
    },
    '5920725115505214': {  # dwc 支付宝3.5%（10---3000），qq1.8%（10---1000）。do结算 新 鑫支付
        'API_KEY': '0E42AE5201A5A206D8AA0CBF4876A23A20180725115505',
        'gateway': 'http://xinfugood.com:8081/trade/doPay.do',
        'query_gateway': 'http://xinfugood.com:8081/trade/quickQuery.do',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


# MD5(merchantId+"pay"+totalAmount+corp_flow_no+商户秘钥code)
def generate_sign(d, key):
    s = d['merchantId'] + 'pay' + d['totalAmount'] + d['corp_flow_no'] + key
    _LOGGER.info("xin1pay sign str: %s", s)
    return _gen_sign(s)


# MD5(merchantId+corp_flow_no+reqMsgId+respType+商户密钥code)
def generate_notify_sign(d, key):
    s = d['merchantId'] + d['corp_flow_no'] + d['reqMsgId'] + d['respType'] + key
    _LOGGER.info("xin1pay notify sign str: %s", s)
    return _gen_sign(s)


# MD5(merchantId+reqMsgId+ corp_flow_no+商户秘钥code)
def generate_query_sign(d, key):
    s = d['merchantId'] + d['corp_flow_no'] + key
    _LOGGER.info("xin1pay query sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("xin1pay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 支付宝扫码传“ZFBZF”
# 微信扫码传
# “WXZF”
# QQ扫码传
# “QQSM”
# JD扫码传
# “JD”
# 银联扫码“UPAY”
# H5 QQ“H5QQSM”
# H5支付宝“H5ZFB”
# H5微信“H5WXIN”
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'H5WXIN'
    elif service == 'alipay':
        payType = 'H5ZFB'
    elif service == 'qq':
        payType = 'H5QQSM'
    else:
        payType = 'H5QQSM'
    return payType


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchantId', app_id),
        ('totalAmount', '%.2f' % pay_amount),
        ('desc', 'charge'),
        ('corp_flow_no', str(pay.id)),
        ('model', _get_pay_type(service)),
        ('notify_url', '{}/pay/api/{}/xin1pay/{}/'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('client_ip', _get_device_ip(info)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("xin1pay create: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("xin1pay create charge data: %s %s", response.status_code, response.text)
    return {'charge_info': json.loads(response.text)['Msg'].replace('HTTPS://QR.ALIPAY.COM/', 'https://qr.alipay.com/')}


# 00
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("xin1pay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['corp_flow_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('xin1pay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['respCode'])
    trade_no = data['reqMsgId']
    total_fee = float(data['amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '00':
        _LOGGER.info('xin1pay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merchantId', app_id),
        ('corp_flow_no', str(pay_order.id)),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info('xin1pay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('xin1pay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['Code'])
        total_fee = float(data['totalAmount'])
        trade_no = data['reqMsgId']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        if trade_status == '00':
            _LOGGER.info('xin1pay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
